package com.myspringsecurity.config;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWTVerifier;
import com.myspringsecurity.entity.Result;
import com.myspringsecurity.filter.JwtVerifyFilter;
import com.myspringsecurity.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/11/1 18:21
 * @description：springsecurity配置类
 * @modified By：
 * @version:
 */
@Configuration
public class MySpringSecurityConfig {
    @Autowired
    JWTUtil jwtUtil;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private JwtVerifyFilter jwtVerifyFilter;
    //定义表单规则，以及过滤规则
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception{
        //把自定义过滤器添加到UsernamePasswordAutocayionFilter前
        http.addFilterBefore(jwtVerifyFilter, UsernamePasswordAuthenticationFilter.class);

        http.formLogin()
//                .loginPage("/login.html")
                //该路径没有绝对的控制层，交予springSecurity完成登录功能
                 .loginProcessingUrl("/login")
//                .successForwardUrl("/success")
                .successHandler(successHandler())
                .permitAll();
        http.cors();
        //禁用跨域伪造
        http.csrf().disable();
        //其他请求必须认证后才能访问
        http.authorizeRequests().anyRequest().authenticated();
        return http.build();
    }
    private AuthenticationSuccessHandler successHandler() {
        return (request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //生成token 按照用户名和用户权限
            Map<String, Object> map = new HashMap<>();
            User principal = (User) authentication.getPrincipal();
            String jwt = jwtUtil.createJWT(map);
            //获取当前用户的名称
            String username = principal.getUsername();
            //获取用户权限
            Collection<GrantedAuthority> authorities = principal.getAuthorities();
            //strea流 把集合中原生的类型转化为另一种类型
            List<String> list = authorities.stream().map(item -> item.getAuthority()).collect(Collectors.toList());
            map.put("username",username);
            map.put("authorities",list);
            String token = jwtUtil.createJWT(map);
            //封装到公共json对象中
            Result result=new Result(200,"登录成功",token);
            String json = JSONUtil.toJsonStr(result);
            writer.print(json);

            writer.flush();
            writer.close();
        };
    }
}
